/** 
 * Copyright (c) 2003-2007 Wonders Information Co.,Ltd. All Rights Reserved.
 * 5-6/F, 20 Bldg, 481 Guiping RD. Shanghai 200233,PRC
 *
 * This software is the confidential and proprietary information of Wonders Group.
 * (Research & Development Center). You shall not disclose such
 * Confidential Information and shall use it only in accordance with 
 * the terms of the license agreement you entered into with Wonders Group. 
 *
 * Distributable under GNU LGPL license by gun.org
 */

package com.wondersgroup.framework.widget.taglib.form;

import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import com.wondersgroup.framework.widget.annotations.WidgetTag;
import com.wondersgroup.framework.widget.annotations.WidgetTagAttribute;
import com.wondersgroup.framework.widget.library.extjs.form.ExtField;
import com.wondersgroup.framework.widget.library.wonders.WondersHtmlForm;
import com.wondersgroup.framework.widget.util.OutputUtils;
import com.wondersgroup.framework.widget.util.TagUtils;
import com.wondersgroup.framework.widget.validation.annotation.TagValidate;
import com.wondersgroup.framework.widget.validation.annotation.TypeValidate;
import com.wondersgroup.framework.widget.validation.annotation.ValueValidate;

/**
 * @author likejun
 * @version $Revision$ 2010-3-18
 * @author (lastest modification by $Author$)
 * @since 4.0
 */

@WidgetTag(name = "form", tldTagClass = "com.wondersgroup.framework.widget.taglib.form.FormTag", description = "Widget Form提供了ajax的提交方式，支持客户端验证，事件提交，优化视图状态")
@TagValidate
public class FormTag extends AbstractFormTag {

    // 表单的请求方式（GET/POST）
    @ValueValidate({ "post", "get" })
    private String method = "post";

    // 是否ajax提交
    @TypeValidate
    private boolean ajax;

    // 是否标准提交
    private boolean standardSubmit;

    // 表单操作地址
    private String url;

    // 表单操作基础参数
    private String urlParams;

    // 等待消息
    private String waitMsg;

    // 超时设置
    private int timeout = 30;

    // 是否包含文件上传
    @TypeValidate
    private boolean fileUpload;

    // 错误提示方式
    @ValueValidate({ "firstalert", "allalert", "print" })
    private String errorStyle = "firstalert";

    // 表单模式（NEW：新建；UPDATE：更新；VIEW：查看）
    private String mode;

    public boolean isAjax() {
        return ajax;
    }

    @WidgetTagAttribute(description = "是否ajax提交")
    public void setAjax(boolean ajax) {
        this.ajax = ajax;
        this.standardSubmit = !ajax;
    }

    public boolean isStandardSubmit() {
        return standardSubmit;
    }

    public void setStandardSubmit(boolean standardSubmit) {
        this.standardSubmit = standardSubmit;
    }

    public String getMethod() {
        return method;
    }

    @WidgetTagAttribute(description = "表单的请求方式,默认为post,限选:post,get")
    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    @WidgetTagAttribute(description = "表单操作地址")
    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrlParams() {
        return urlParams;
    }

    @WidgetTagAttribute(description = "表单操作基础参数")
    public void setUrlParams(String urlParams) {
        this.urlParams = urlParams;
    }

    public String getWaitMsg() {
        return waitMsg;
    }

    @WidgetTagAttribute(description = "等待消息")
    public void setWaitMsg(String waitMsg) {
        this.waitMsg = waitMsg;
    }

    public int getTimeout() {
        return timeout;
    }

    @WidgetTagAttribute(description = "超时设置,默认为30s")
    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public boolean isFileUpload() {
        return fileUpload;
    }

    @WidgetTagAttribute(description = "是否包含文件上传")
    public void setFileUpload(boolean fileUpload) {
        this.fileUpload = fileUpload;
    }

    public String getErrorStyle() {
        return errorStyle;
    }

    @WidgetTagAttribute(description = "错误提示方式，可选值['firstalert','allalert','print']，分别代表弹出第一个错误，弹出全部错误，以及打印所有错误在表单头部")
    public void setErrorStyle(String errorStyle) {
        this.errorStyle = errorStyle;
    }

    public String getMode() {
        return mode;
    }

    @WidgetTagAttribute(description = "表单模式（NEW：新建；UPDATE：更新；VIEW：查看）")
    public void setMode(String mode) {
        this.mode = mode;
    }

    @Override
    public void processStartTagContent() throws JspException {

        pageContext.getRequest().setAttribute(FormConstants.FORM_ITEMS,
                this.getId() + "_items");
        // add by xieguojun
        String formGridArray = this.getId() + "GridArray";
        pageContext.getRequest().setAttribute(FormConstants.FORM_GRIDARRAY,
                formGridArray);

        List<ExtField> fields = new ArrayList<ExtField>();
        pageContext.getRequest()
                .setAttribute(FormConstants.FORM_FIELDS, fields);

        StringBuffer text = new StringBuffer();
        text.append("<div id= '" + getId() + "_div' class=\"x-form\">");
        text.append(OutputUtils.writeJSFile(pageContext,
                "wonders/form/wonders-form-min.js"));
        text.append("<script>");
        text.append("var " + super.getFormItems() + " = new Array;\n");
        // add by xieguojun
        text.append("var ").append(formGridArray).append(" = new Array;\n");
        text.append("</script>");

        // 2013/01/16 xieguojun增加
        HttpServletRequest request = (HttpServletRequest) pageContext
                .getRequest();
        text.append(String.format("<script src='%s%s'></script>", request
                .getContextPath(), "/resource/scripts/form.failure.patch.js"));

        TagUtils.getInstance().write(pageContext, text.toString());
    }

    @Override
    public void processEndTagContent() throws JspException {
        List<ExtField> fields = (List<ExtField>) pageContext.getRequest()
                .getAttribute(FormConstants.FORM_FIELDS);

        WondersHtmlForm form = new WondersHtmlForm(getId());
        BeanUtils.copyProperties(this, form);
        form.setFields(fields);
        form.setItems(super.getFormItems());
        form.setRenderTo(getId() + "_div");

        StringBuffer text = new StringBuffer();
        text.append(OutputUtils.ExtOnReady(form));
        text.append("</div>");
        TagUtils.getInstance().write(pageContext, text.toString());

        pageContext.getRequest().removeAttribute(FormConstants.FORM_ITEMS);
        pageContext.getRequest().removeAttribute(FormConstants.FORM_FIELDS);
        // add by xieguojun
        pageContext.getRequest().removeAttribute(FormConstants.FORM_GRIDARRAY);

    }
}
